package com.vdimitr.happycube.puzzle.matrix;

import com.vdimitr.happycube.puzzle.piece.PuzzlePieceConstants;

/**
 * This class is responsible for determining if puzzle pieces can fit together
 * based on their matrix representation. General rule is that two puzzle pieces
 * fit together if they don't have overlapping cells.
 * 
 * @author vasileios.dimitriadis
 * 
 */
public class MatrixMatcher {

	/**
	 * No need to instantiate this class
	 */
	private MatrixMatcher() {
	}

	/**
	 * Compares the last column of the left matrix with the first column of the
	 * right matrix.
	 * 
	 * @param leftMatrix
	 *            matrix representing left puzzle piece
	 * @param rightMatrix
	 *            matrix representing right puzzle piece
	 * @return True iff both left and right corresponding cells do not contain 1
	 */
	public static boolean matricesMatchLeftToRight(int[][] leftMatrix,
			int[][] rightMatrix) {
		int[] leftColumn = MatrixUtils.getLastColumn(leftMatrix);
		int[] rightColumn = MatrixUtils.getFirstColumn(rightMatrix);
		return matricesMatch(leftColumn, rightColumn);
	}

	/**
	 * Compares the last row of the top matrix with the first row of the bottom
	 * matrix.
	 * 
	 * @param topMatrix
	 *            matrix representing top puzzle piece
	 * @param bottomMatrix
	 *            matrix representing bottom puzzle piece
	 * @return True iff both top and bottom corresponding cells do not contain 1
	 */
	public static boolean matricesMatchTopToBottom(int[][] topMatrix,
			int[][] bottomMatrix) {
		int x1 = PuzzlePieceConstants.PUZZLEPIECE_MATRIX_SIZE - 1;// last row
		int x2 = 0;// first row
		return matricesMatch(topMatrix[x1], bottomMatrix[x2]);
	}

	/**
	 * Check if two matrices can fit together. That is they do not contain both
	 * of them 1 at the same cell
	 * 
	 * @param matrix1
	 *            a row or column
	 * @param matrix2
	 *            a row or column
	 * @return True iff both matrices do not both 1 at the same cell
	 */
	private static boolean matricesMatch(int[] matrix1, int[] matrix2) {
		for (int i = 0; i < PuzzlePieceConstants.PUZZLEPIECE_MATRIX_SIZE; i++) {
			if ((matrix1[i] + matrix2[i]) > 1) {
				return false;
			}
		}
		return true;
	}
}
